package cn.com.callback

import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import org.json.JSONObject

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.time.Instant
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.kh.getProperty;

/**
 *
 * @Title: aipHSTRecycle_operation_timing
 * @Description:华盛证券 回收定时任务查询接口
 * @author: xrm
 * @date 2022-12-20 15:52:00
 *
 */

public class job_HSTRecycle_operation_timing implements CallBackInvoke{
    private static final Log log=LogFactory.getLog(job_HSTRecycle_operation_timing.class);

    public void doCallBack(EliteBean eliteBean,String callBack,Map map,String body) {

        log.debug("-------------------------start job_HSTRecycle_operation_timing 开始调用-----------------");

        String inData = "";
        String outData = "";
        String totalData = "";
        String totalData2 = "";
        String dataSourceID = "dataSource";


        try {
            List hst_recycle_ruleslist = eliteBean.chaxun_sql("select recovery_guid,xc_recovery_time from hst_recycle_rules where 1=1 and NOW()>= take_effectstarttime and NOW()<=take_effectendtime", "dataSource");//查询回收规则
            log.debug("hst_recycle_ruleslist:" + hst_recycle_ruleslist.size());
            if (hst_recycle_ruleslist.size() > 0) {
                int arrInt = hst_recycle_ruleslist.size();
                for (int i = 0; i < arrInt; i++) {
                    String recovery_guid = hst_recycle_ruleslist.get(i).get("recovery_guid");//回收规则id
                    String xc_recovery_time = hst_recycle_ruleslist.get(i).get("xc_recovery_time");//下次回收时间

                    List nowlist = eliteBean.chaxun_sql("select DATE_FORMAT('" + xc_recovery_time + "','%Y-%m-%d') as nowtime", "dataSource");//获取下次回收时间年月日
                    def nowtime = nowlist.get(0).get("nowtime");

                    List nowlist2 = eliteBean.chaxun_sql("select DATE_FORMAT(NOW(),'%Y-%m-%d') as nowtime2", "dataSource");//获取现在时间年月日
                    def nowtime2 = nowlist2.get(0).get("nowtime2");

                    if (KHUtil.isNull(xc_recovery_time) || nowtime == nowtime2) {//下次回收时间为空或者等于此时执行
                        String sign_time = Instant.now().getEpochSecond();
                        log.debug("解析信息-" + "sign_time: " + sign_time);
                        String injson = "{\"recovery_guid\"" + ":" + "\"" + recovery_guid + "\"}"
                        log.debug("injson:" + injson);

                        totalData = Querypromocode(eliteBean, injson, dataSourceID);
                    }
                }

            }

            outData = "{\"result\":\"1\",\"message\":\"处理成功\",\"data\":[]}";

            log.debug("*************************************************************************Querypromocode2*****************************************************************************");
            totalData2 = Querypromocode2(eliteBean);


        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            outData = "{\"result\":\"-1\",\"message\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
        }

        log.debug(outData);
    }

    //回收查询接口 URI:	aipHSTRecycle_operation
    public static String Querypromocode(EliteBean eliteBean, String injson, String dataSourceID) {

        long startTime = System.currentTimeMillis();
        log.debug("处理开始时间:" + startTime);

        long endTime = System.currentTimeMillis();

        String reJson = null;
        String tagname = "";
        try {
            String doURL = "";

            String sysurl = KHDBConfig.getAPIURL(eliteBean, "API-InnerDomain");//配置本地接口地址

            doURL = sysurl + "/aipHSTRecycle_operation";

            log.debug("doURL:" + doURL);
            Map<String, String> headMap = new HashMap<String, String>();
            headMap.put("Content-Type", "application/x-www-form-urlencoded");
            def getResult = Util.doHttpPostUseHead(doURL, injson, "UTF-8", 10000, 0, headMap);
            log.debug("getResult:" + getResult);
        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            reJson = "{\"result\":\"-1\",\"message\":\"接口异常\",\\\"lastid\\\":\"0\"}";
        }
        return reJson;
    }

    //调集解绑接口
    public static String Querypromocode2(EliteBean eliteBean) {

        long startTime = System.currentTimeMillis();
        log.debug("调集解绑时间:" + startTime);
        String reJson2 = null;

        try {
            List hst_assign_hislist = eliteBean.chaxun_sql("select DISTINCT c.CUSTOMER_ID,a.CUSTOMER_GUID as CUSTOMER_GUID from assign_his a left join customer c on a.CUSTOMER_GUID=c.CUSTOMER_GUID left join objective O on a.OBJECTIVE_GUID=O.OBJECTIVE_GUID and o.map_id='MY48ZX' where a.SUCCESS_GUID='接口回收数据' and O.cancellationstatus is null AND TO_DAYS(O.retaindeadline)=TO_DAYS(NOW())", "dataSource");//查询保留有效期到期的回收名单
            log.debug("hst_assign_hislist:"+hst_assign_hislist.size());
            if (hst_assign_hislist.size() > 0) {
                int arrInt = hst_assign_hislist.size();
                for (int i = 0; i < arrInt; i++) {
                    //华盛接口连续调用可能异常 添加1S睡眠
                    Thread.sleep(1 * 1000);

                    String customer_id = hst_assign_hislist.get(i).get("CUSTOMER_ID");//华盛号
                    String customer_guid = hst_assign_hislist.get(i).get("CUSTOMER_GUID");//assign_his客户id

                    List success_guid_list = eliteBean.chaxun_sql("select SUCCESS_GUID from assign_his  where CUSTOMER_GUID='" + customer_guid + "' ORDER BY ASSIGNDATE desc LIMIT 1","dataSource");
                    String success_guid = success_guid_list.get(0).get("SUCCESS_GUID");//assign_his类型

                    if(success_guid != "接口回收数据" && success_guid != "账号管理回收数据"){
                        log.debug(customer_guid+" :非回收名单，跳出循环!");
                        continue;
                    }

                    //调用解绑接口
                    String injson="{\"hsNo\""+":"+"\""+customer_id+"\",\"divideType\":2}"
                    String doURL ="";
                    String sysurl = getProperty.get("crmurl");//配置本地接口地址
                    doURL = sysurl+"aipHSTBindCounselor";

                    log.debug("doURL:" + doURL);
                    Map<String, String> headMap = new HashMap<String, String>();
                    headMap.put("Content-Type", "application/x-www-form-urlencoded");
                    def getResult = Util.doHttpPostUseHead(doURL, injson, "UTF-8", 10000, 0, headMap);
                    log.debug("getResult:" + getResult);

                    JSONObject jsonObject = new JSONObject(getResult);
                    String code = GetJV(jsonObject, "result");
                    log.debug("绑定接口返回code：" + code);
                    //api接口 成功 则分配
                    if (code == "1") {
                        log.debug("解绑回收接口成功！");
                    }else if (code == "10013") {
                        String updateObjSQL = "update objective set cancellationstatus='注销' where customer_guid='"+customer_guid+"' and MAP_ID='MY48ZX'  ";
                        def updateObjSQLresult= eliteBean.update(updateObjSQL, "dataSource");
                        log.debug("客户已注销！标识更新："+updateObjSQLresult);
                    }else{
                        log.debug("解绑接口失败！");
                    }
                }

            }

        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            reJson2 = "{\"result\":\"-1\",\"message\":\"接口异常\",\\\"lastid\\\":\"0\"}";
        }
        return reJson2;
    }

    // 解析Json值
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;

        try {
            Rev_Value = String.valueOf(inJson.getBoolean(getKey));
        } catch (Exception e6) {
            try {
                Rev_Value = inJson.getString(getKey);
            } catch (Exception e5) {
                try {
                    Rev_Value = String.valueOf(inJson.getInt(getKey));
                } catch (Exception e4) {
                    try {
                        Rev_Value = String.valueOf(inJson.getLong(getKey));
                    } catch (Exception e11) {
                        try {
                            Rev_Value = String.valueOf(inJson.getDouble(getKey));
                        } catch (Exception e1) {
                            try {
                                Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                            } catch (Exception e2) {
                                try {
                                    Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                                } catch (Exception e3) {
                                    Rev_Value = "";
                                }
                            }
                        }
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            }
        }
        return Rev_Value;
    }

}
